import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button, Cell, NavBar, ProductCard, Sticky } from 'react-vant'
import { ArrowLeft, WeappNav } from '@react-vant/icons'
import './index.less'
import { useEffect, useState, useMemo } from 'react'
import axios from 'axios'
import { Provider, useSelector } from 'react-redux'
import { RootState } from '../../../store'
import { store } from '../../../store'

const PaymentContent = () => {
  const selectedAddress = useSelector((state: RootState) => state.address.selectedAddress);

  // 获取订单支付页面数据
  const [paymentInfo, setPaymentInfo] = useState<any>([])
  const getPaymentApi = async () => {
    const { data } = await axios.get(`http://localhost:3000/getCartGoods?checked=${true}`)
    setPaymentInfo(data.cartGoods)
  }

  useEffect(() => {
    getPaymentApi()
  }, [])

  // 倒计时状态
  const [countdown, setCountdown] = useState(15 * 60); // 15分钟，以秒为单位
  const [isExpired, setIsExpired] = useState(false);

  // 格式化倒计时显示
  const formatCountdown = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}分${remainingSeconds}秒`;
  };

  // 倒计时效果
  useEffect(() => {
    if (countdown > 0 && !isExpired) {
      const timer = setInterval(() => {
        setCountdown(prev => {
          if (prev <= 1) {
            clearInterval(timer);
            setIsExpired(true);
            Taro.showToast({
              title: '支付超时，订单已失效',
              icon: 'none',
              duration: 2000
            });
            setTimeout(() => {
              Taro.navigateBack();
            }, 2000);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [countdown, isExpired]);

  // 处理支付按钮点击
  const handlePayment = async () => {
    if (isExpired) {
      Taro.showToast({
        title: '订单已超时，请重新下单',
        icon: 'none'
      });
      return;
    }

    if (!selectedAddress) {
      Taro.showToast({
        title: '请选择收货地址',
        icon: 'none'
      });
      return;
    }

    try {
      const { data } = await axios.post('http://localhost:3000/createOrder', {
        address: selectedAddress // 将选中的地址信息传给后端
      });

      if (data.code === 200) {
        window.location.href = data.data.payUrl;
      } else {
        Taro.showToast({
          title: '创建订单失败',
          icon: 'none'
        });
      }
    } catch (error) {
      Taro.showToast({
        title: '支付发起失败',
        icon: 'none'
      });
    }
  };

  // 计算价格
  const {
    totalPrice,     // 商品总价
    finalPrice,     // 合计总价（8折）
    pointsDiscount  // 积分抵扣
  } = useMemo(() => {
    // 计算商品总价
    const total = paymentInfo.reduce((sum, item) => {
      return sum + (item.goodsPrice * item.goodsNum);
    }, 0);

    // 计算8折后的价格
    const final = total * 0.8;

    // 计算积分抵扣（总价与折后价的差值）
    const discount = total - final;

    return {
      totalPrice: total.toFixed(2),
      finalPrice: final.toFixed(2),
      pointsDiscount: discount.toFixed(2)
    };
  }, [paymentInfo]);

  return (
    <View className='payment-container'>
      <NavBar
        title="待支付"
        leftText={<ArrowLeft />}
        rightText={<WeappNav />}
        style={{ color: '#fff' }}
        onClickLeft={() => { Taro.navigateBack() }}
        fixed
        placeholder
      />

      <Sticky offsetTop={46}>
        <View className='order-countdown'>
          {formatCountdown(countdown)}后自动取消
        </View>
      </Sticky>
      {/* 收货地址选择 */}
      <Cell
        title={selectedAddress ? (
          <View>
            <View>{selectedAddress.username} {selectedAddress.phone}</View>
            <View className="address-detail">{selectedAddress.address.join(' ')} {selectedAddress.dAddress}</View>
          </View>
        ) : '请选择收货地址'}
        isLink
        onClick={() => Taro.navigateTo({ url: '/user/pages/address/index' })}
      />

      <View className='order-items'>
        <Cell.Group>
          {paymentInfo.map((item, index) => {
            return <Cell key={index}>
              <View className='shop-info'>
                <View className='shop-name'>
                  {item.shopName}
                </View>
              </View>
              <ProductCard
                num={item.goodsNum}
                price={item.goodsPrice}
                desc={item.goodsDes}
                title={item.goodsName}
                thumb={item.goodsImgsrc}
              />
            </Cell>
          })}

        </Cell.Group>
      </View>

      <View className='price-detail'>
        <Cell title='商品总价' value={`¥${totalPrice}`} />
        <Cell title='积分抵扣' value={`-¥${pointsDiscount}`} valueClass='discount-value' />
        <Cell title='合计总价' value={`¥${finalPrice}`} valueClass='total-value' />
      </View>

      <View className='order-info'>
        <Cell title='订单备注' value='我是备注内容' />
      </View>
      <div style={{ marginBottom: 50 }}></div>

      <View className='bottom-bar'>
        <Button
          block
          type='danger'
          className='pay-button'
          disabled={isExpired}
          onClick={handlePayment}
        >
          {isExpired ? '订单已超时' : '立即支付'}
        </Button>
      </View>
    </View>
  )
}

const Payment = () => {
  return (
    <Provider store={store}>
      <PaymentContent />
    </Provider>
  )
}

export default Payment
